package com.cskaoyan.gateway.controller.user;

import com.cskaoyan.gateway.form.user.UserForm;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.IKaptchaService;
import com.mall.user.ILoginService;
import com.mall.user.IVerifyService;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.mall.user.intercepter.TokenIntercepter.ACCESS_TOKEN;

/**
 * @Description:
 * @Author: JK、YiXinhao
 * @Date: create in 2021/7/20 20:28
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Reference(timeout = 3000, check = false, retries = 0)
    ILoginService loginService;

    @Reference(timeout = 3000, check = false, retries = 0)
    IKaptchaService kaptchaService;

    @Reference(timeout = 30000, check = false, retries = 0)
    IVerifyService iVerifyService;

    /**
     * 登录POST
     * @param
     * @return
     */
    //请求 URL: http://www.maimaimai.ltd/user/login
    //请求负载：{"userName":"test","userPwd":"test","captcha":"fx03"}
    //响应负载：{"success":true,"message":"success","code":200,"result":{"code":"000000","msg":"成功","id":62,"username":"test","phone":null,"email":null,"sex":null,"address":null,"file":"https://gper.club/server-img/avatars/000/00/00/user_origin_30.jpg?time1565591384242","description":null,"points":null,"balance":null,"state":1,"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ3bGd6cyIsImV4cCI6MTYyNjkxNzk3NywidXNlciI6IjRCNUM1RkY5OTQ2RjZCQ0M3NkNGODI2RTlCN0UwQjVBQ0Y1RkE0QkNFNzNCRTQ2MkI0QjQ4OTUzNkZEMTZBNjVCNkMwMDY0ODA1N0JDMjlFRDBFMjRCQkVDMDg5MzZGRkIwRkRFMDI2OUJFQzNDMjZGMzdGNkQ3NjY2RjRBN0RFNDNFNUY2RURBNjk3NDg3RTFBNzk4NDdDNjE3Nzg3MEVGODAxRTRBNEQ2RUREMTdCQkE4ODIwODI4NTM3MjJBQUExNDYyQTU2MzVDMTFDOUQ4QTFFMDNBNUY3MzE3MEQwNzIxQ0E1RUYwNzc4OUE2NDkyN0Q4NTg2NEE4QzBCREUifQ.D1A5pBRX1w_b-FnViBpSjBgCtjnv5wNrK1TcnddF8aE"},"timestamp":1626831577800}
    //响应负载：{"code":500,"success":false,"message":"token已失效","timestamp":1626831467959}
    @Anoymous
    @PostMapping("/login")
    public ResponseData userLogin(@RequestBody UserForm form, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        UserLoginRequest request = new UserLoginRequest();
        request.setUserName(form.getUserName());
        request.setPassword(form.getUserPwd());

        //校验验证码captcha，还要从cookie里面取得验证码对应的uuid
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        String uuid = CookieUtil.getCookieValue(httpServletRequest, "kaptcha_uuid");
        kaptchaCodeRequest.setUuid(uuid);
        kaptchaCodeRequest.setCode(form.getCaptcha());
        //验证这个图形验证码是不是对的，这个方法里面利用到了reddis
        KaptchaCodeResponse response = kaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        //如果验证结果不对，直接报错即可
        if (!response.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            return new ResponseUtil<>().setErrorMsg(response.getMsg());
        }
        //到这里说明图形验证码是对的，再去service层检查用户名和密码对不对
        UserLoginResponse userLoginResponse = loginService.userLogin(request);
        //如果登录返回结果的code是正确的
        if (SysRetCodeConstants.SUCCESS.getCode().equals(userLoginResponse.getCode())) {
            //咱们还要判断这个账户是否被激活
            Boolean ifVerified = iVerifyService.ifUserVerified(form.getUserName());
            //如果未被激活，要返回错误值，提示去邮箱里激活
            if (!ifVerified) {
                return new ResponseUtil<>().setErrorMsg("您的账号还未激活，请您去邮箱里查看我们发送给您的激活链接，激活后即可正常使用，谢谢");
            }
            //把token放进cookie里面，把新的cookie放进httpServletResponse里面
            Cookie cookie = CookieUtil.genCookie(ACCESS_TOKEN, userLoginResponse.getToken(), "/", 24 * 60 * 60);
            cookie.setHttpOnly(true);
            httpServletResponse.addCookie(cookie);
//            return new ResponseUtil<>().setData(userLoginResponse);
            return new ResponseUtil<>().setData(userLoginResponse,"success");
        }
        return new ResponseUtil<>().setErrorMsg(userLoginResponse.getMsg());
    }

    /**
     * 登录Get，确定登录状态
     * @param request
     * @return
     */
    //请求 URL: http://www.maimaimai.ltd/user/login
    //响应负载：{"success":true,"message":"success","code":200,"result":{"uid":62,"file":"https://gper.club/server-img/avatars/000/00/00/user_origin_30.jpg?time1565591384242","username":"test"},"timestamp":1626873892256}
    @Anoymous
    @GetMapping("/login")
    public ResponseData userLoginVerify(HttpServletRequest request) {
        UserLoginStatusRequest userLoginStatusRequest = new UserLoginStatusRequest();

        String token = CookieUtil.getCookieValue(request, ACCESS_TOKEN);
        if (StringUtils.isEmpty(token)) {
            return new ResponseUtil<>().setErrorMsg("token 已失效");
        }
        userLoginStatusRequest.setToken(token);

        UserLoginStatusResponse userLoginStatusResponse = loginService.userLoginVerify(userLoginStatusRequest);
        if (SysRetCodeConstants.SUCCESS.getCode().equals(userLoginStatusResponse.getCode())) {
            return new ResponseUtil<>().setData(userLoginStatusResponse.getUserLoginStatusResponseDto());
        }

        return new ResponseUtil<>().setErrorMsg(userLoginStatusResponse.getMsg());

    }


    //请求 URL: http://www.maimaimai.ltd/user/loginOut
    //响应负载：{"success":true,"message":"success","code":200,"result":null,"timestamp":1587710244802}
    @Anoymous
    @GetMapping("/loginOut")
    public ResponseData userloginOut(HttpServletResponse httpServletResponse){
        //要把cookie里面的token这一项去掉
        Cookie cookie = new Cookie(ACCESS_TOKEN, null);
        //把生命设置为0
        cookie.setMaxAge(0);
        //设置路径
        cookie.setPath("/");
        //放进response中，实现去除
        httpServletResponse.addCookie(cookie);
        return new ResponseUtil<>().setData(null);
    }
}
